package org.zoomdev.zoom.aop.modules;


import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;

import java.util.Map;

import static org.objectweb.asm.Opcodes.ASM9;
import static org.objectweb.asm.Opcodes.NEW;

public final class ScanModuleVisitor extends ClassVisitor {


    final Map<String, MethodWithTypeConfig> descriptorMap;

    private MethodWithTypeConfig config;

    ScanModuleVisitor(Map<String, MethodWithTypeConfig> descriptorMap) {
        super(ASM9);
        this.descriptorMap = descriptorMap;
    }


    @Override
    public MethodVisitor visitMethod(int access, String methodName, String methodDesc, String signature, String[] exceptions) {
        //System.out.println("visit method:" + name + "====> " + descriptor);
        MethodVisitor mv = super.visitMethod(access, methodName, methodDesc, signature, exceptions);
        if (methodName.equals("<init>")) {
            return mv;
        }


        this.config = descriptorMap.get(methodName + methodDesc);
        //System.out.println("访问方法: " + methodName + methodDesc);
        if (this.config == null) {
            return mv;
        }
        // System.out.println("找到配置: " + methodName + methodDesc);
        return new MethodVisitor(api, mv) {
            @Override
            public void visitTypeInsn(int opcode, String type) {
                if (opcode == NEW && shouldRecordType(type)) {
                    //System.out.println("在方法"+methodName+"中创建新对象: " + type);
                    if (config != null) {
                        config.setType(type);
                    }
                }
                super.visitTypeInsn(opcode, type);
            }

            private boolean shouldRecordType(String type) {
                // 过滤JDK基础类和工具类
                return !type.startsWith("java");
            }

        };
    }

}
